package com.hospital.config;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.hospital.realm.UserRealm;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;


@Configuration
public class ShiroConfig {
	//realm  数据域
    @Bean
    public UserRealm userRealm(HashedCredentialsMatcher hashedCredentialsMatcher,MemoryConstrainedCacheManager cacheManager) {
        UserRealm userRealm = new UserRealm();
        userRealm.setCacheManager(cacheManager);
        userRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return userRealm;
    }
    //配置shiro核心过滤器
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        Map<String, String> filtermap = new LinkedHashMap<String, String>();
        //toLogin/login界面可以未认证直接访问
        filtermap.put("/user/login", "anon");
        filtermap.put("/css/**", "anon");
        filtermap.put("/layuiadmin/**/**", "anon");
        filtermap.put("/layuiadmin/**", "anon");
        filtermap.put("/layui_ext/**", "anon");
        filtermap.put("/js/**", "anon");
        filtermap.put("/public/**", "anon");
        filtermap.put("/images/**", "anon");

        //未认证都不允许通过
        filtermap.put("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filtermap);
        //如果访问的页面未认证   跳转到登陆页面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        return shiroFilterFactoryBean;
    }
    
  //安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager( UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //用来跟加密的密码进行比对的bean
    //凭证匹配器
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //设置比较规则
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        //迭代1次
        hashedCredentialsMatcher.setHashIterations(1);
        return hashedCredentialsMatcher;
    }
    //设置认证缓存
    @Bean
    public MemoryConstrainedCacheManager cacheManager() {
    	return new MemoryConstrainedCacheManager();
    }
    //shiro 与thymeleaf的整合
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }
}
